﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Xml;
using System.IO;

namespace MPMovieCatalog.Util.Grabber
{
    class TMDbImageGrabber
    {
        private ArrayList m_imageList = new ArrayList();

        public TMDbImageGrabber() { }

        public int Count
        {
            get { return m_imageList.Count; }
        }

        public string this[int index]
        {
            get
            {
                if (index < 0 || index >= m_imageList.Count) return string.Empty;
                return (string)m_imageList[index];
            }
        }

        public void Search(string imdbNumber)
        {
            if (string.IsNullOrEmpty(imdbNumber)) return;

            m_imageList.Clear();

            string tmdbURL = string.Format("http://api.themoviedb.org/2.1/Movie.getImages/ru/xml/b61ba5397fb9de4c5124742d05b3119e/{0}", imdbNumber);
            string tmdbPage = string.Empty;

            WebSession tmdbSession = new WebSession();
            if (tmdbSession.Retrieve(tmdbURL, Encoding.GetEncoding("UTF-8"), out tmdbPage))
            {
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(new StringReader(tmdbPage));

                XmlNode root = xmlDoc.DocumentElement;
                XmlNodeList imageNodes = root.SelectNodes("//movies/movie/images/poster/image[@size='original']");

                if (imageNodes != null && imageNodes.Count > 0)
                {
                    foreach (XmlNode imageNode in imageNodes)
                    {
                        XmlAttributeCollection attrColl = imageNode.Attributes;
                        XmlAttribute attr = (XmlAttribute)attrColl.GetNamedItem("url");
                        if (attr != null && !string.IsNullOrEmpty(attr.Value))
                        {
                            m_imageList.Add(attr.Value);
                        }
                    }
                }
            }
        }
    }
}
